﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ATW.MT.CommonClass;
using ATW.MT.BUS;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Text.RegularExpressions;
using System.Collections;

namespace ATW.MT.Common
{
    public partial class AjaxHandler : Page
    {
        bus_D_user user = new bus_D_user();
        bus_D_SystemArgs ds = new bus_D_SystemArgs();
        bus_D_Item di = new bus_D_Item();
        bus_T_production pro = new bus_T_production();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserInfo"] == null)
            {
                Server.Transfer("../Main/Login.aspx");
                return;
            }
            if (!IsPostBack)
            {
                if (Request.Form["Handler"] != null || Request.QueryString["Handler"] != null)
                {
                    string handler = Request.Form["Handler"] == null ? Request.QueryString["Handler"] : Request.Form["Handler"];
                    if (handler == "addUser")
                    {
                        writeRes(AddUser());
                    }
                    if (handler == "isUserExist")
                    {
                        writeRes(IsUserExist());
                    }
                    if (handler == "levelUser")
                    {
                        writeRes(levelUser());
                    }
                    if (handler == "levelModule")
                    {
                        writeRes(levelModule());
                    }
                    if (handler == "levelModuleEdit")
                    {
                        writeRes(levelModuleEdit());
                    }
                    if (handler == "isNameExist")
                    {
                        writeRes(isLevelNameExist());
                    }
                    if (handler == "addGroup")
                    {
                        writeRes(addGroup());
                    }
                    if (handler == "editGroup")
                    {
                        writeRes(editGroup());
                    }
                    if (handler == "getCus")
                    {
                        writeRes(getCus());
                    }
                    if (handler == "editCus")
                    {
                        writeRes(editCus());
                    }
                    if (handler == "getSeller")
                    {
                        writeRes(getSellerList());
                    }
                    if (handler == "getLevel")
                    {
                        writeRes(getlevel());
                    }
                    if (handler == "getProduction")
                    {
                        writeRes(getProduction());
                    }
                    if (handler == "addProduction")
                    {
                        writeRes(addProduction());
                    }
                    if (handler == "editProduction")
                    {
                        writeRes(editProduction());
                    }
                }
            }
        }
        //是否存在
        private string IsUserExist()
        {
            string res = "";
            try
            {
                string account = Request.Form["account"];
                if (user.IsUserExist(account))
                {
                    return "true";
                }
                return "false";
            }
            catch (Exception ex)
            {

            }
            return res;
        }
        //新增用户
        private string AddUser()
        {
            try
            {
                string account = Request.Form["account"].Trim();
                string pwd = Request.Form["pwd"].Trim();
                string levelClass = Request.Form["level"];

                #region 校验

                if (!common.filterChar(account, 50) || !common.filterRequestString(account))
                {
                    return "账号长度超出范围或者含有非法字符";
                }
                if (!common.filterChar(pwd, 50) || !common.filterRequestString(pwd))
                {
                    return "密码长度超出范围或者含有非法字符";
                }
                #endregion
                int result = user.UserAdd(account, pwd, levelClass);
                if (result > 0)
                {
                    return "OK";
                }
                else
                {
                    return "操作失败";
                }
            }
            catch (Exception ex)
            {
                return "操作失败:" + ex.Message;
            }

        }
        //用户组成员
        private string levelUser()
        {
            string res = "";
            try
            {
                string level = Request.QueryString["level"];
                DataTable dt = user.LevelUser(level);
                res = JsonConvert.SerializeObject(dt);

            }
            catch (Exception ex)
            {
                return "-1";
            }
            return res;
        }
        //用户组权限
        private string levelModule()
        {
            string res = "";
            try
            {
                string level = Request.QueryString["level"];
                DataTable dt = new DataTable();
                dt = user.LevelModule(level);
                res = JsonConvert.SerializeObject(dt);
            }
            catch (Exception ex)
            {
                return "-1";
            }
            return res;
        }
        //用户组权限
        private string levelModuleEdit()
        {
            string res = "";
            try
            {
                string level = Request.QueryString["level"];
                DataTable dt = new DataTable();
                dt = user.LevelModuleEx(level);
                res = JsonConvert.SerializeObject(dt);
            }
            catch (Exception ex)
            {
                return "-1";
            }
            return res;
        }
        //组名是否存在
        private string isLevelNameExist()
        {
            string res = "";
            try
            {
                string name = Request.QueryString["name"];
                if (user.IsGroupNameExist(name))
                {
                    res = "true";
                }
                else
                {
                    res = "false";
                };
            }
            catch (Exception ex)
            {

            }
            return res;
        }
        //创建组
        private string addGroup()
        {
            string res = "";
            try
            {
                string name = Request.Form["name"];
                string list = Request.Form["mid"];
                string[] _item = list.Split(new char[] { ',' });
                ArrayList al = new ArrayList();
                for (int i = 0; i < _item.Length; i++)
                {
                    Regex r = new Regex("[0-9]+");
                    string mid = r.Match(_item[i]).ToString();
                    string sql = user.UserSetAuthor(name, mid);
                    al.Add(sql);
                }
                bool flag = user.ExAL(al);
                if (flag)
                {
                    res = "OK";
                }
                else
                {
                    res = "Err";
                }
            }
            catch (Exception ex)
            {
            }
            return res;
        }
        private string editGroup()
        {
            string res = "";
            try
            {
                string name = Request.Form["name"];
                string list = Request.Form["mid"];
                string[] _item = list.Split(new char[] { ',' });
                ArrayList al = new ArrayList();
                al.Add(user.UserDelAuthor(name));
                for (int i = 0; i < _item.Length; i++)
                {
                    Regex r = new Regex("[0-9]+");
                    string mid = r.Match(_item[i]).ToString();
                    string sql = user.UserSetAuthor(name, mid);
                    al.Add(sql);
                }

                bool flag = user.ExAL(al);
                if (flag)
                {
                    res = "OK";
                }
                else
                {
                    res = "Err";
                }
            }
            catch (Exception ex)
            {
            }
            return res;
        }
        //获取用户信息
        private string getCus()
        {
            BUS.bus_T_appuser user = new bus_T_appuser();
            string res = "";
            try
            {
                string uid = Request.QueryString["uid"];
                if (common.filterChar(uid))
                {
                    DataTable dt = user.UserSingleQuery(uid);
                    res = JsonConvert.SerializeObject(dt);
                }
            }
            catch (Exception ex)
            {
                return "-1";
            }
            return res;
        }
        //修改用户信息
        private string editCus()
        {
            BUS.bus_T_appuser user = new bus_T_appuser();
            try
            {
                string uid = Request.Form["uid"];
                string rank = Request.Form["rank"];
                string rate = Request.Form["rate"];
                string belongTo = Request.Form["belongTo"];
                string currency = Request.Form["currency"];

                int _uid, _rank, _currency;
                float _rate = 0;
                if (uid != "" && !int.TryParse(uid, out _uid))
                {
                    return "invalid args 'uid'";
                }
                if (rank != "" && !int.TryParse(rank, out _rank))
                {
                    return "invalid args 'rank'";
                }
                if (currency != "" && !int.TryParse(currency, out _currency))
                {
                    return "invalid args 'currency'";
                }
                if (rate != "" && !float.TryParse(rate, out _rate))
                {
                    return "invalid args 'rate'";
                }
                string minRate = ds.GetSysArgs("MinRate");
                string maxRate = ds.GetSysArgs("MaxRate");
                float _minRate = float.Parse(minRate);
                float _maxRate = float.Parse(maxRate);
                if (_rate < _minRate || _rate > _maxRate)
                {
                    return "out of range";
                }
                if (belongTo != "" && !common.filterChar(belongTo))
                {
                    return "invalid args 'belongto'";
                }
                int result = user.UserUpdate(rank, rate, currency, belongTo, uid);
                if (result > 0)
                {
                    return "OK";
                }
                else
                {
                    return "no effects";
                }

            }
            catch (Exception ex)
            {
                return "DB　Error" + ex.Message;
            }
        }
        //获取销售列表
        private string getSellerList()
        {
            BUS.bus_T_appuser user = new bus_T_appuser();
            string res = "";
            try
            {
                string name = Request.QueryString["name"];
                if (common.filterChar(name))
                {
                    DataTable dt = user.UserPagerQuery(name, "5", 1, int.MaxValue);
                    res = JsonConvert.SerializeObject(dt);
                }
            }
            catch (Exception ex)
            {
                return "-1";
            }
            return res;
        }
        //检查能否设置子项级别
        private string getlevel()
        {
            string res = "";
            string cid = Request.QueryString["cid"];
            string level = Request.QueryString["level"];
            try
            {
                if (level == "A" || level == "B" || di.canLevelBeSet(cid, level))
                {
                    res = "OK";
                }
                else
                {
                    res = "NO";
                }

            }
            catch (Exception ex)
            {

            }
            return res;
        }
        //获取产品
        private string getProduction()
        {
            string res = "";
            try
            {
                string pid = Request.QueryString["pid"];
                if (!common.filterChar(pid))
                {
                    return "illigal args";
                }
                DataTable dt = pro.ProductionSingleQuery(pid);
                res = JsonConvert.SerializeObject(dt);
            }
            catch (Exception ex)
            {

            }
            return res;
        }
        //新增产品
        private string addProduction()
        {
            string res = "";
            try
            {
                string name = Request.Form["name"];
                string imgurl = Request.Form["url"];
                string rate = Request.Form["rate"];
                if (!common.filterChar(name) || !common.filterChar(imgurl) || !common.filterChar(rate))
                {
                    return "illigal args";
                }
                if (pro.ProductionAdd(name, rate, imgurl))
                {
                    return "OK";
                }
                else
                {
                    return "DB Error";
                }
            }
            catch (Exception ex)
            {

            }
            return res;
        }
        //修改产品
        private string editProduction()
        {
            string res = "";
            try
            {
                string name = Request.Form["name"];
                string imgurl = Request.Form["url"];
                string rate = Request.Form["rate"];
                string pid = Request.Form["proid"];
                if (!common.filterChar(name) || !common.filterChar(imgurl) || !common.filterChar(rate) || !common.filterChar(pid))
                {
                    return "illigal args";
                }
                if (pro.ProductionEdit(name, imgurl, rate, pid))
                {
                    return "OK";
                }
                else
                {
                    return "DB Error";
                }
            }
            catch (Exception ex)
            {

            }
            return res;
        }
        private void writeRes(string s)
        {
            Response.Clear();
            Response.Write(s);
            Response.End();
        }
    }
}